/**
 * 天地图影像
 */
function addTDTimg() {
    var tiandituSatelliteLayer = new ol.layer.Tile({
        source: new ol.source.XYZ({
            url: "http://t3.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=008a8816d2eee25a677670273eaee891",
            crossOrigin: "anonymous"
        }),
        title:"天地图影像"
    });
    tiandituSatelliteLayer.setZIndex(0);
    mapApp.olMap.addLayer(tiandituSatelliteLayer)
}

/**
 * 移除天地图影像
 */
function removeTDTimg() {
    mapApp.olMap.removeLayer(getLayers_HD("天地图影像",mapApp.olMap));

}

/**
 * 谷歌影像注记
 */
function addGoogleH() {
    var googleMapLayer = new ol.layer.Tile({
        source: new ol.source.XYZ({
            url: 'http://www.google.cn/maps/vt?lyrs=h@189&gl=cn&x={x}&y={y}&z={z}'
        }),
        title:"谷歌影像注记"
    });
    mapApp.olMap.addLayer(googleMapLayer)
}

/**
 * 移除谷歌影像注记
 */
function removeGoogleH() {
    mapApp.olMap.removeLayer(getLayers_HD("谷歌影像注记",mapApp.olMap));

}

/**
 * 加载超图iserver发布的山东矢量地图
 */
function addSuperMapShandonProvince() {
    var url = "http://101.200.150.193:8090/iserver/services/map-provincetouming/rest/maps/provincetouming";
    var layer = new ol.layer.Tile({
        source: new ol.source.TileSuperMapRest({
            url: url,
            wrapX: true
        }),
        title:"山东省界",
        projection: 'EPSG:4326'
    });
    layer.setZIndex(1);
    mapApp.olMap.addLayer(layer)
}

/**
 * 加载山东省市级界线图
 */
function addSuperMapShandonCity() {
    var url = "http://101.200.150.193:8090/iserver/services/map-cityborder/rest/maps/cityborder_deal";
    var layer = new ol.layer.Tile({
        source: new ol.source.TileSuperMapRest({
            url: url,
            wrapX: true
        }),
        title:"山东省市界",
        projection: 'EPSG:4326'
    });
    layer.setZIndex(1);
    mapApp.olMap.addLayer(layer)
}

/**
 * 移除山东矢量地图
 */
function removeShandonProvince() {
    mapApp.olMap.removeLayer(getLayers_HD("山东省界",mapApp.olMap));

}

/**
 * 移除山东市界图
 */
function removeShandongCity() {
    mapApp.olMap.removeLayer(getLayers_HD("山东省市界",mapApp.olMap));
}

/**
 * 加载非遗分布地点
 */
function addSuperMapFeiYi() {
    var url = "http://101.200.150.193:8090/iserver/services/map-feiwuzhi/rest/maps/feiwuzhi";
    var layer = new ol.layer.Tile({
        source: new ol.source.TileSuperMapRest({
            url: url,
            wrapX: true
        }),
        title:"非遗分布地点",
        projection: 'EPSG:4326'
    });
    layer.setZIndex(100);
    mapApp.olMap.addLayer(layer)
}

/**
 * 移除非遗分布地点
 */
function removeFeiYi() {
    mapApp.olMap.removeLayer(getLayers_HD("非遗分布地点",mapApp.olMap));

}

/**
 * 加载非遗申请人分布
 */
function addFeiYiPeople() {
    var url = "http://101.200.150.193:8090/iserver/services/map-feiyipeople/rest/maps/feiyipeople";
    var layer = new ol.layer.Tile({
        source: new ol.source.TileSuperMapRest({
            url: url,
            wrapX: true
        }),
        title:"非遗申请人",
        projection: 'EPSG:4326'
    });
    layer.setZIndex(200);
    mapApp.olMap.addLayer(layer)
}

/**
 * 移除非遗申请人分布
 */
function removeFeiYiPeople() {
    mapApp.olMap.removeLayer(getLayers_HD("非遗申请人",mapApp.olMap));

}

/**
 * 加载纠偏以后的百度矢量地图
 */
function addBaiduVec(){
    var extent = [72.004, 0.8293, 137.8347, 55.8271];
    var baiduMercator = new ol.proj.Projection({
        code: 'baidu',
        extent: ol.extent.applyTransform(extent, projzh.ll2bmerc),
        units: 'm'
    });

    ol.proj.addProjection(baiduMercator);
    ol.proj.addCoordinateTransforms('EPSG:4326', baiduMercator, projzh.ll2bmerc, projzh.bmerc2ll);
    ol.proj.addCoordinateTransforms('EPSG:3857', baiduMercator, projzh.smerc2bmerc, projzh.bmerc2smerc);

    var bmercResolutions = new Array(19);
    for (var i = 0; i < 19; ++i) {
        bmercResolutions[i] = Math.pow(2, 18 - i);
    }
    var urls = [0, 1, 2, 3, 4].map(function (sub) {
        //return 'http://shangetu' + sub +'.map.bdimg.com/it/u=x={x};y={y};z={z};v=009;type=sate&fm=46&udt=20150601';
        return 'http://online2.map.bdimg.com/onlinelabel/?qt=tile&x={x}&y={y}&z={z}&styles=pl&udt=20151021&scaler=1&p=1';
    });

    var baidu = new ol.layer.Tile({
        source: new ol.source.XYZ({
            projection: 'baidu',
            maxZoom: 18,
            tileUrlFunction: function (tileCoord) {
                var x = tileCoord[1];
                var y = tileCoord[2];
                var z = tileCoord[0];
                var hash = (x << z) + y;
                var index = hash % urls.length;
                index = index < 0 ? index + urls.length : index;
                return urls[index].replace('{x}', x).replace('{y}', y).replace('{z}', z);
            },
            tileGrid: new ol.tilegrid.TileGrid({
                resolutions: bmercResolutions,
                origin: [0, 0],
                extent: ol.extent.applyTransform(extent, projzh.ll2bmerc),
                tileSize: [256, 256]
            })
        }),
        title:"百度矢量"
    });
    mapApp.olMap.addLayer(baidu)
}

/**
 * 测量距离与面积
 * state：true启用，false关闭
 * type 为line和mian
 */

var sketch;
var helpLineTooltipElement;
var helpPolygonTooltipElement;
var helpLineTooltip;
var helpPolygonTooltip;
var measureLineTooltipElement;
var measurePolygonTooltipElement;
var measureLineTooltip;
var measurePolygonTooltip;
var draw;
function celiangjuli(state, type) {
    if (state) {
        if (draw) {
            mapApp.olMap.removeInteraction(draw);
            addInteraction(type);
        } else {
            addInteraction(type);
        }
    } else {
        if (type === "line") {
            mapApp.olMap.removeInteraction(draw);
            mapApp.olMap.removeLayer(lineLayer)
            // var overLayers = mapApp.olMap.getOverlays()
            // for (var i = 0; i < overLayers.getLength(); i++) {
            //     var lineOverLayer = overLayers[i]
            //     if (lineOverLayer.element.id === "line") {
            //         mapApp.olMap.removeOverlay(overLayers.a[i])
            //     }
            // }
             mapApp.olMap.getOverlays().clear();
        } else {
            mapApp.olMap.removeInteraction(draw);
            mapApp.olMap.removeLayer(PolygonLayer);
            mapApp.olMap.getOverlays().clear();
            // var overLayers = mapApp.olMap.getOverlays()
            // for (var i = 0; i < overLayers.getLength(); i++) {
            //     var polygonOverLayer = overLayers[i]
            //     if (polygonOverLayer.element.id === "polygon") {
            //         mapApp.olMap.removeOverlay(overLayers.a[i])
            //     }
            // }
        }

    }
}

/**
 * 测距相关
 * @param line
 * @returns {*}
 */
function formatLength(line) {
    var wgs84Sphere = new ol.Sphere(6378137);
    var coordinates = line.getCoordinates();
    var length = 0;
    for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
        length += wgs84Sphere.haversineDistance(coordinates[i], coordinates[i + 1]);
    }
    var output;
    if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) +
            ' ' + 'km';
    } else {
        output = (Math.round(length * 100) / 100) +
            ' ' + 'm';
    }
    return output;
}

/**
 * 测面相关
 * @param polygon
 * @returns {*}
 */
function formatArea(polygon) {
    var wgs84Sphere = new ol.Sphere(6378137);
    var coordinates = polygon.getLinearRing(0).getCoordinates();
    var area = Math.abs(wgs84Sphere.geodesicArea(coordinates));
    var output;
    if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) +
            ' ' + 'km<sup>2</sup>';
    } else {
        output = (Math.round(area * 100) / 100) +
            ' ' + 'm<sup>2</sup>';
    }
    return output;
}

/**
 * 加入测量地图交互
 * @param parm
 */
function addInteraction(parm) {
    var type = (parm === 'mian' ? 'Polygon' : 'LineString');
    console.log(type)
    console.log(type === "LineString")
    if (type === "LineString") {
        var source = new ol.source.Vector({wrapX: false});
        lineLayer = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: "rgba(255,255,255,0.5)"
                }),
                stroke: new ol.style.Stroke({
                    color: "blue"
                })
            }),
            title: "line",
            zIndex: 10000
        });
        mapApp.olMap.addLayer(lineLayer);
        draw = new ol.interaction.Draw({
            source: source,
            type: type,
            title: "drawLine"
        });
        mapApp.olMap.addInteraction(draw);
        createLineMeasureTooltip();
        createLineHelpTooltip();

        var listener;
        draw.on('drawstart',
            function (evt) {
                // set sketch
                sketch = evt.feature;
                /** @type {module:ol/coordinate~Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;
                listener = sketch.getGeometry().on('change', function (evt) {
                    var geom = evt.target;
                    var output;
                    output = formatLength(geom);
                    tooltipCoord = geom.getLastCoordinate();

                    measureLineTooltipElement.innerHTML = output;
                    measureLineTooltip.setPosition(tooltipCoord);
                });
            }, this);

        draw.on('drawend',
            function () {
                measureLineTooltipElement.className = 'tooltip tooltip-static';
                measureLineTooltip.setOffset([0, -7]);
                // unset sketch
                sketch = null;
                // unset tooltip so that a new one can be created
                measureLineTooltipElement = null;
                createLineMeasureTooltip();
                new ol.Observable(listener);
            }, this);
    } else if (type == "Polygon") {
        var source = new ol.source.Vector({wrapX: false});
        PolygonLayer = new ol.layer.Vector({
            source: source,
            style: new ol.style.Style({
                fill: new ol.style.Fill({
                    color: "rgba(255,255,255,0.5)"
                }),
                stroke: new ol.style.Stroke({
                    color: "blue"
                })
            }),
            title: " polygon",
            zIndex: 10000
        });
        mapApp.olMap.addLayer(PolygonLayer);
        draw = new ol.interaction.Draw({
            source: source,
            type: type,
            title: "drawPolygon"
        });
        mapApp.olMap.addInteraction(draw);
        createPolygonMeasureTooltip();
        createPolygonHelpTooltip();

        var listener;
        draw.on('drawstart',
            function (evt) {
                // set sketch
                sketch = evt.feature;
                /** @type {module:ol/coordinate~Coordinate|undefined} */
                var tooltipCoord = evt.coordinate;
                listener = sketch.getGeometry().on('change', function (evt) {
                    var geom = evt.target;
                    var output;
                    output = formatArea(geom);
                    tooltipCoord = geom.getInteriorPoint().getCoordinates();

                    measurePolygonTooltipElement.innerHTML = output;
                    measurePolygonTooltip.setPosition(tooltipCoord);
                });
            }, this);

        draw.on('drawend',
            function () {
                measurePolygonTooltipElement.className = 'tooltip tooltip-static';
                measurePolygonTooltip.setOffset([0, -7]);
                // unset sketch
                sketch = null;
                // unset tooltip so that a new one can be created
                measurePolygonTooltipElement = null;
                createPolygonMeasureTooltip();
                new ol.Observable(listener);
            }, this);
    }

}

/**
 * Creates a new help tooltip
 */
/**
 * 测量相关绘制面
 */
function createPolygonHelpTooltip() {
    if (helpPolygonTooltipElement) {
        helpPolygonTooltipElement.parentNode.removeChild(helpPolygonTooltipElement);
    }
    helpPolygonTooltipElement = document.createElement('div');
    helpPolygonTooltipElement.className = 'tooltip hidden';
    helpPolygonTooltip = new ol.Overlay({
        element: helpPolygonTooltipElement,
        offset: [15, 0],
        positioning: 'center-left'
    });
    mapApp.olMap.addOverlay(helpPolygonTooltip);
}

/**
 * Creates a new measure tooltip
 */
function createPolygonMeasureTooltip() {
    if (measurePolygonTooltipElement) {
        measurePolygonTooltipElement.parentNode.removeChild(measurePolygonTooltipElement);
    }
    measurePolygonTooltipElement = document.createElement('div');
    measurePolygonTooltipElement.setAttribute("id", "polygon");
    measurePolygonTooltipElement.className = 'tooltip tooltip-measure';
    measurePolygonTooltip = new ol.Overlay({
        element: measurePolygonTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
        id: 2
    });
    mapApp.olMap.addOverlay(measurePolygonTooltip);

}

/**
 * Creates a new help tooltip
 */
function createLineHelpTooltip() {
    if (helpLineTooltipElement) {
        helpLineTooltipElement.parentNode.removeChild(helpLineTooltipElement);
    }
    helpLineTooltipElement = document.createElement('div');
    helpLineTooltipElement.className = 'tooltip hidden';
    helpLineTooltip = new ol.Overlay({
        element: helpLineTooltipElement,
        offset: [15, 0],
        positioning: 'center-left'
    });
    mapApp.olMap.addOverlay(helpLineTooltip);
}

/**
 * Creates a new measure tooltip
 */
function createLineMeasureTooltip() {
    if (measureLineTooltipElement) {
        measureLineTooltipElement.parentNode.removeChild(measureLineTooltipElement);
    }
    measureLineTooltipElement = document.createElement('div');
    measureLineTooltipElement.setAttribute("id", "line");
    measureLineTooltipElement.className = 'tooltip tooltip-measure';
    measureLineTooltip = new ol.Overlay({
        element: measureLineTooltipElement,
        offset: [0, -15],
        positioning: 'bottom-center',
        id: 1
    });
    mapApp.olMap.addOverlay(measureLineTooltip);

}

/**
 * 根据非遗feature的id查询非遗点
 */
function queryById(id) {

        url = "http://101.200.150.193:8090/iserver/services/data-feiwuzhi/rest/data";

        var idsParam = new SuperMap.GetFeaturesByIDsParameters({
            IDs: [id],
            datasetNames: ["feiwuzhi:非遗清单"]
        });
        new ol.supermap.FeatureService(url).getFeaturesByIDs(idsParam, function (serviceResult) {
            var vectorSource = new ol.source.Vector({
                features: (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features),
                wrapX: false
            });
            var resultLayer = new ol.layer.Vector({
                source: vectorSource,
                // 设置样式，颜色为红色，线条粗细为4个像素
                style: new ol.style.Style({
                    image: new ol.style.RegularShape({
                        radius: 8,
                        points: 10,
                        stroke: new ol.style.Stroke({
                            color: "red",
                            width:8
                        })
                    }),
                }),
            });
            mapApp.olMap.addLayer(resultLayer);
        });
}


/**
 * 通过SQL查询(查询泰安市为例)
 */
function queryBySQL() {
        url = "http://101.200.150.193:8090/iserver/services/data-feiwuzhi/rest/data";

        var sqlParam = new SuperMap.GetFeaturesBySQLParameters({
            queryParameter: {
                name: "非遗清单@feiwuzhi",
                attributeFilter: "PROVINCE = '山东省泰安市'"
            },
            datasetNames: ["feiwuzhi:非遗清单"]
        });
        new ol.supermap.FeatureService(url).getFeaturesBySQL(sqlParam, function (serviceResult) {
            var vectorSource = new ol.source.Vector({
                features: (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features),
                wrapX: false
            });
            var resultLayer = new ol.layer.Vector({
                source: vectorSource,
                // 设置样式，颜色为红色，线条粗细为4个像素
                style: new ol.style.Style({
                    image: new ol.style.RegularShape({
                        radius: 8,
                        points: 10,
                        stroke: new ol.style.Stroke({
                            color: "red",
                            width:8
                        })
                    }),
                }),
            });
            mapApp.olMap.addLayer(resultLayer);
        });

}


/**
 * 几何查询
 */
function queryByPolygonGeometry() {
    mapApp.olMap.removeLayer(getLayers_HD("几何查询多边形",mapApp.olMap));
    mapApp.olMap.removeLayer(getLayers_HD("几何查询结果",mapApp.olMap));

    mapApp.olMap.removeInteraction(draw);


    url = "http://101.200.150.193:8090/iserver/services/data-feiwuzhi/rest/data";


    var source = new ol.source.Vector({wrapX: false});
    var PolygonLayer = new ol.layer.Vector({
        source: source,
        title:"polygon",
        style: new ol.style.Style({
            fill: new ol.style.Fill({
                color: "rgba(255,255,255,0.5)"
            }),
            stroke: new ol.style.Stroke({
                color: "blue"
            })
        }),
        title: " polygon",

    });
    //mapApp.olMap.addLayer(PolygonLayer);


    //绘制地图交互
    var interaction = new ol.interaction.Draw({
        source: source,
        type: "Polygon"
    });
    mapApp.olMap.addInteraction(interaction);


    // interaction.on('drawstart', function (evt) {
    //     feature = evt.feature;
    //
    // });
    //绘制完成以后的操作
    interaction.on('drawend', function () {
        setTimeout(function(){
            //console.log(PolygonLayer.getSource().getFeatures());
            var polygon=PolygonLayer.getSource().getFeatures()[0].getGeometry();
            var polygonSource = new ol.source.Vector({
                features: [new ol.Feature(polygon)],
                wrapX: false
            });
            var vectorLayer = new ol.layer.Vector({
                source: polygonSource,
                title:"几何查询多边形",
                //绘制的多边形的样式
                style: new ol.style.Style({
                    stroke: new ol.style.Stroke({
                        color: 'red',
                        width: 3
                    }),

                })
            });
            mapApp.olMap.addLayer(vectorLayer);

            var geometryParam = new SuperMap.GetFeaturesByGeometryParameters({
                datasetNames: ["feiwuzhi:非遗清单"],
                geometry: polygon,
                spatialQueryMode: "INTERSECT"
            });
            new ol.supermap.FeatureService(url).getFeaturesByGeometry(geometryParam, function (serviceResult) {
                var vectorSource = new ol.source.Vector({
                    features: (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features),
                    wrapX: false
                });
                var resultLayer = new ol.layer.Vector({
                    source: vectorSource,
                    title:"几何查询结果",
                    // 设置样式，颜色为红色，线条粗细为4个像素
                    style: new ol.style.Style({
                        image: new ol.style.Icon({
                            opacity: 1,
                            src: "../assets/images/marker-icon.png"
                        })
                    }),

                });
                mapApp.olMap.addLayer(resultLayer);

                var resultt=resultLayer.getSource().getFeatures()[0].values_.TYPE;

                console.log(resultt);
            });
        },1000)


        mapApp.olMap.removeInteraction(interaction);



    });

    
}


/**
 * 属性查询
 * @param state
 */
function propertiesQuery(state) {
    url = "http://101.200.150.193:8090/iserver/services/data-feiwuzhi/rest/data";

    if(state){
         // $("#popup").show()
        var polygon = new ol.geom.Polygon([[[113.9939,33.664948], [113.000446,38.413866], [123.818057,38.58736], [124.452763,33.433873]]]);
        var featureService = new ol.supermap.FeatureService(url);
        var getFeatureParams = new SuperMap.GetFeaturesByGeometryParameters({
            toIndex: -1,
            datasetNames: ["feiwuzhi:非遗清单"],
            geometry: polygon,
            spatialQueryMode: "INTERSECT"
        });
        featureService.getFeaturesByGeometry(getFeatureParams, function (serviceResult) {
            var features = (new ol.format.GeoJSON()).readFeatures(serviceResult.result.features);

            // for (var i = 0; i < features.length; i++){
            //     if(features[i].getProperties().TITLE=="梁祝传说"){
            //         console.log(features[i].getProperties().TITLE)
            //         features[i].setStyle(new ol.style.Style({
            //             image: new ol.style.Icon(({
            //                 anchor: [0.5, 0.9],
            //                 src: 'assets/img/marker-icon.png'
            //             }))
            //         }));
            //
            //     }
            // }

            vectorSource.addFeatures(features);

            //新建一个变量
            mapApp.olMap.oldCityF=new Object();

            mapApp.olMap.oldCityF.key=mapApp.olMap.on('click',function pointermoveLinstener(e) {
                $("#popup").show()

                mapApp.olMap.forEachFeatureAtPixel(e.pixel, function (feature) {
                    if (feature.getProperties().TYPE) {


                        mapApp.olMap.getTargetElement().style.cursor = 'click';


                        content = document.getElementById('popup-content');
                        var overlay = new ol.Overlay(({
                            element: document.getElementById('popup'),
                            autoPan: true,

                            autoPanAnimation: {
                                duration: 250
                            },
                            offset: [0, -20]
                        }));

                        var contentHTML = "非遗类型："+feature.getProperties().TYPE+"</br>"+"非遗名称："+feature.getProperties().TITLE+"</br>"+"非遗地点："+feature.getProperties().PROVINCE;
                        var poptitle=feature.getProperties().TITLE;
                        $.ajax({
                            type: "GET",
                            contentType: "application/x-www-form-urlencoded",
                            url: "http://localhost:8089/feiyi/getTitle",
                            data: {
                                "title": poptitle,
                            },
                            xhrFields: {withCredentials: true},
                            success: function (data) {
                                parent.detailData = data.data;
                                var popimg = "/image/" + parent.detailData.path1;

                                //var contentHTML2="<br>"+"<p style='color: #1c72bd;padding-left: 30%;padding: 10px 30%; cursor: pointer;'>查看详情</p>";//href='../html/jie/detail.html'
                                //var contentHTML3="<br>"+"<img style='width: 200px' src='"+popimg+"\' />"

                                var contentHTML = "<tr>\n" +
                                    "    <td style=\"padding: 5px\">\n" +
                                    "        <p><span>非遗类型：</span><span>"+feature.getProperties().TYPE+"</span></p>\n" +
                                    "        <p><span>非遗名称：</span><span>"+feature.getProperties().TITLE+"</span></p>\n" +
                                    "        <p><span>非遗地点：</span><span>"+feature.getProperties().TYPE+"</span></p>\n" +
                                    "        <img style='width: 200px' src='"+popimg+ "' />\n" +
                                    "    </td>\n" +
                                    "    <td style=\"padding: 5px\">\n" +
                                    "        <p style='color:black ;padding-left: 30%;padding: 10px 30%; cursor: pointer;'><span id='popdetail'>查看详情</span></p>\n" +
                                    "    </td>\n" +
                                    "</tr>"

                                content.innerHTML = contentHTML;

                                var popdetailFun = document.getElementById("popdetail");
                                popdetailFun.addEventListener('click', showDetail, false); //鼠标单击的时候调用showMes这个函数
                                function showDetail() {
                                    $(window.parent.document).find('#contentIframe').attr('src', './html/jie/introduce.html');
                                }
                            },
                            //失败的回调函数
                            error: function (data) {
                                console.log(data.statusText)
                            }
                        });
                        overlay.setPosition(feature.getGeometry().getCoordinates());
                        mapApp.olMap.addOverlay(overlay);

                    }
                }, {
                    //检测点击的点的范围
                    hitTolerance: 10
                });

            }.bind(this));
        });




        //添加查询结果图层
        var vectorSource = new ol.source.Vector({
            wrapX: false
        });
        var resultLayer = new ol.layer.Vector({
            source: vectorSource,
        });

        //添加点图层
        var addPointsSource = new ol.source.Vector({
            wrapX: false
        });
        addPointsLayer = new ol.layer.Vector({
            source: addPointsSource,
        });

        mapApp.olMap.addLayer(addPointsLayer);
        mapApp.olMap.addLayer(resultLayer);
    }else{
        $("#popup").hide();
        if(mapApp.olMap.oldCityF.key){
            var keyy=mapApp.olMap.oldCityF.key;
            ol.Observable.unByKey(keyy);
        }


    }





}


/**
 *
 * 全图
 */

function quantu(){
    var bounds = [114.972,34.096,
        122.596,38.348];
    mapApp.olMap.getView().fit(bounds,mapApp.olMap.getSize());

}

/**
 * 定位
 */

/* 定位搜索按钮 */
$("#search2DBtn").click(function () {

    mapApp.olMap.removeLayer(getLayers_HD("zuobiaodingwei",mapApp.olMap));

    var ld = $(".search-2D-inp").val();
    if (ld != "") {
        var ldList = ld.split(",");
        if (ldList.length == 2) {
            positioning(ldList[0],ldList[1]);
        } else {
            alert("请输入正确的坐标！");
        }
    } else {
        alert("请输入坐标！");
    }
});
function positioning(lon,lat) {

    var View = mapApp.olMap.getView();
    if (lon && lat) {
        View.setCenter([parseFloat(lon), parseFloat(lat)]);
        View.setZoom(14);
        //创建图标特性
        var iconFeature = new ol.Feature({
            geometry: new ol.geom.Point([lon, lat]),
            name: "my Icon"
        });
        //创建空的矢量容器
        var source = new ol.source.Vector({wrapX: false});
        //将图标特性添加进矢量中
        source.addFeature(iconFeature);
        //创建图标样式
        var iconStyle = new ol.style.Style({
            image: new ol.style.Icon({
                opacity: 1,
                src: "../assets/images/marker-icon.png"
            })
        });
        //创建图标层
        var zuobiaodingweiLayer = new ol.layer.Vector({
            source: source,
            style: iconStyle,
            title: "zuobiaodingwei"
        });
        mapApp.olMap.addLayer(zuobiaodingweiLayer);
    } else {
        removLayer(mapApp.olMap, "zuobiaodingwei");
    }
}

/**
 * 透明度
 * state：true启用，false关闭
 */
function TouMingDu(state, value) {
        //var layers = mapApp.olMap.getLayers().getArray();
        if (state) {
            // for (var i = layers.length - 1; i > 0; i--) {
            //     layers[i].setOpacity(value);

            // }

            getLayers_HD("高德地图",mapApp.olMap).setOpacity(value)
        }
    }

/**
 * 2维截屏
 * state：true启用，false关闭
 */
function mapJiePing2d(state) {
    if (state) {
        mapApp.olMap.once('postcompose', function (event) {
            var canvas = event.context.canvas;
            var img = new Image();
            img.crossOrigin = "Anonymous";//解决跨域图片问题，就是上面提及的
            if (navigator.msSaveBlob) {
                navigator.msSaveBlob(canvas.msToBlob(), 'map.png');
            } else {
                canvas.toBlob(function(blob) {
                    saveAs(blob, 'map.png');
                });
            }
        });
        mapApp.olMap.renderSync();
    }
}

/**
 * 加载高德地图
 */
function addAMap() {
    //高德地图
    var gaodeMapLayer = new ol.layer.Tile({
        source: new ol.source.XYZ({
            url:'http://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}'
        }),
        title:"高德地图"
    });
    mapApp.olMap.addLayer(gaodeMapLayer)

}

/**
 * 根据图层title获取图层
 */
function getLayers_HD(layersName, map) {
    if (map) {
        return loopMap(layersName, map)
    } else {
        return loopMap(layersName, mapApp.olMap)
    }
    function loopMap(layersName, Map) {
        var mapLayers = Map.getLayers().getArray()
        if (layersName instanceof Array) {
            var resultLayers = [];
            for (var j = 0; j < layersName; j++) {
                for (var i = 0; i < mapLayers.length; i++) {
                    if (mapLayers[i].getProperties().title == layerName[j]) {
                        resultLayers.push(mapLayers[i]);
                    }
                }
            }
            return resultLayers;
        } else {
            if (layersName) {
                for (var i = 0; i < mapLayers.length; i++) {
                    if (mapLayers[i].getProperties().title == layersName) {
                        return mapLayers[i];
                    }
                }
            }
        }
    }
}




